package com.example.datedemo2.service.tools;

import com.example.datedemo2.service.dto.ResponseResult;
import org.springframework.dao.DuplicateKeyException;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class StaticTools {

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
    private static SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM W");
    private static SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static ResponseResult getModifyResult(int i, Object Sample) {
        try {
            int updateNum = i;
            if (updateNum == 0) {
                return new ResponseResult(0, "失败");
            }
        } catch (Exception e) {
            boolean Duplicate = e instanceof DuplicateKeyException;
            if (Duplicate) {
                return new ResponseResult(13, "此项目，此年 此周/此月 已有记录 或 主键重复");
            }
            if (Duplicate) {
                return new ResponseResult(4, "未知错误");
            }
        }
        return new ResponseResult(1, "成功");
    }

    // 月份+1纠正
    public static Date tranDate(String monthNumber) {
        Date tempDate = null;
        try {
            tempDate = dateFormat.parse(monthNumber);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar tempCalendar = Calendar.getInstance();
        assert tempDate != null;
        tempCalendar.setTime(tempDate);
        tempCalendar.add(Calendar.MONTH, +1);
        tempDate = tempCalendar.getTime();
        return tempDate;
    }

    // 实际记录时间判定
    public static Date transToWeekNumber(String monthParameter, int weekParameter) throws ParseException {
        // 若为第一周，则 该月首日 为实际记录时间
        if (weekParameter == 1) {
            return dateFormat.parse(monthParameter);
        } else {
            String tempStr = monthParameter + " " + weekParameter;
            return tempFormat.parse(tempStr);
        }
    }

    public static boolean isNormalWeek(String monthParameter, int weekParameter) throws ParseException {

        Date tempDate = dateFormat.parse(monthParameter);
        Date realDate = ymdFormat.parse(ymdFormat.format(transToWeekNumber(monthParameter, weekParameter)));
        Calendar temp = Calendar.getInstance();
        Calendar real = Calendar.getInstance();
        temp.setTime(tempDate);
        real.setTime(realDate);


        if (temp.get(Calendar.YEAR) == real.get(Calendar.YEAR) && temp.get(Calendar.MONTH) == real.get(Calendar.MONTH)) {
            return false;
        } else {
            return true;
        }
    }
}
